var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var version = require('../../config/version.js');
var user = require('../../services/user.js');
var app = getApp();

Component({
  properties: {},

  data: {
    isShow: false,
    winHeight: 0,
    winWidth: 0,
    // 用户授权
    auth: app.globalData.auth,
    userInfo: app.globalData.userInfo,
    hasUserInfo: app.globalData.hasUserInfo,
    hasPhone: app.globalData.hasPhone,
    getUserInfoFail: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    //短信
    phone: '',
    vercode: '',
    returnCode: '',
    disabled: true,
    time: '获取验证码', //倒计时 
    currentTime: 61
  },

  methods: {
    login: function() {
      return new Promise(function(resolve, reject) {
        wx.login({
          success: function(res) {
            if (res.code) {
              //登录远程服务器
              resolve(res);
            } else {
              reject(res);
            }
          },
          fail: function(err) {
            reject(err);
          }
        });
      });
    },

    getUserInfo: function(e) {
      var that = this
      if (e.detail.hasOwnProperty('userInfo') && e.detail.userInfo) {
        app.globalData.auth = true
        that.setData({
          auth: true,
          isShow: false
        })

        let code = null;
        return that.login().then((res) => { //userInfo
          code = res.code;
          wx.getUserInfo({
            withCredentials: true,
            success: function(res_user) {
              //先去登陆        
              wx.request({
                url: api.userAuth,
                data: {
                  platform: "wx",
                  authorizationCode: code,
                  userEncryptrfData: res_user.encryptedData,
                  iv: res_user.iv
                },
                method: 'POST',
                header: {
                  'Content-Type': 'application/json',
                  'accessToken': wx.getStorageSync('token'),
                  'appVersion': version.appVersion,
                  'deviceModel': getApp().globalData.systemInfo.model,
                  'platform': 'wx',
                  'build': version.build,
                  'deviceMachineCode': '',
                  'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
                  'deviceOSVersion': getApp().globalData.systemInfo.system,
                },
                success: function(res) {               
                  if (res.statusCode == 200) {
                    if (res.data.code == 200) {
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;
                      var userInfo = res.data.data.user
                      if (userInfo && !userInfo.avatarUrl){
                        userInfo.avatarUrl = version.defaultAvataUrl
                      }
                      wx.setStorageSync('userInfo', userInfo);
                      app.globalData.userInfo = userInfo
                      app.globalData.hasUserInfo = true
                      app.globalData.auth = true
                      wx.setStorageSync('auth', true);
                      app.globalData.hasPhone = true
                      wx.setStorageSync('hasPhone', true);
                      that.setData({
                        hasPhone: true,
                        isShow: false
                      });
                      that.triggerEvent('myevent', {
                        paramBtoA: {
                          userInfo: userInfo,
                          hasUserInfo: true,
                          auth: true,
                          hasPhone: true,
                        }
                      })                    

                    }

                    if (res.data.code == 301) {//如果没有绑定手机号
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;                     
                      that.setData({
                        isShow: true
                      });
                      that.triggerEvent('myevent', {
                        paramBtoA: {
                          hasPhone: false,
                          userInfo:{},
                          hasUserInfo:false,
                          auth: false
                        }
                      })   
                    }

                  }
                }
              })
              //
            }
          })
        })


      } else {
        this.openSetting();
      }
    },

    loginT: function() {
      console.log('login')
      var that = this
      wx.login({ //不会弹出授权窗口 获取用户的code
        success: function(res) {
          var code = res.code;
          wx.getUserInfo({ //弹出授权窗口 获取用户的头像 昵称等
            success: function(res) {
              app.globalData.userInfo = res.userInfo;
              app.globalData.hasUserInfo = true
              app.globalData.showPhone = true

              that.setData({
                getUserInfoFail: false,
                userInfo: res.userInfo,
                hasUserInfo: true,
                showPhone: true
              })
              //平台登录
            },
            fail: function(res) {
              that.setData({
                getUserInfoFail: true
              })
            }
          })
        }
      })
    },
    //跳转设置页面授权
    openSetting: function() {
      var that = this
      // 调用wx.openSetting打开手机《设置》允许使用数据
      if (wx.openSetting) {
        wx.openSetting({ //如果用户在设置了设置允许了，返回后立刻再次登录
          success: function(res) {
            //尝试再次登录
            that.loginT()
          },
          fail: function(res) {
            wx.showModal({
              title: '微信授权失败',
              content: '为了更好使用同感小程序，请允许获取您的信息！'
            })
          }
        })
      } else {
        wx.showModal({
          title: '授权提示',
          content: '小程序需要您的微信授权才能使用哦~ 错过授权页面的处理方法：删除小程序->重新搜索进入->点击授权按钮'
        })
      }
    },

    close_auth: function() {
      this.setData({
        isShow: false,
      })
    },
    cancleMask: function() {
      // this.setData({
      //   isShow: false
      // })
    },

    getCode: function(options) {
      var that = this;
      var currentTime = that.data.currentTime
      var interval = setInterval(function() {
        currentTime--;
        that.setData({
          time: currentTime + '秒'
        })
        if (currentTime <= 0) {
          clearInterval(interval)
          that.setData({
            time: '重新发送',
            currentTime: 61,
            disabled: false
          })
        }
      }, 1000)
    },

    //验证手机号
    phoneInput: function(e) {
      var phone = e.detail.value
      if (phone.length > 0) {
        this.setData({
          disabled: false,
          phone: e.detail.value
        })
      }
    },
    sendVercode: function() {
      if (!this.data.phone) {
        wx.showModal({
          title: '错误提示',
          content: '手机号不能为空！'
        })
      }
      var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!myreg.test(this.data.phone)) {
        wx.showModal({
          title: '友情提示',
          content: '不是有效的手机号码！'
        })
      }

      util.pututrequest(api.verifyCode + '?phone=' + this.data.phone + '&type=LOGIN' +'&areaCode=86', 'GET').then((res) => {
        if (res && res.code == 200) {
          wx.showToast({
            title: '验证码已经发送到您的手机',
            icon: 'success',
            duration: 2000
          })
          this.getCode();
          this.setData({
            vercode: '',
            disabled: true,
          })
        }
      })
    },
    codeInput: function(e) {
      var code = e.detail.value
      this.setData({
        vercode: code
      })

    },

    regPhone: function() {
      var that = this      
      util.pututrequest(api.bindMobile, 'POST', {
        areaCode: '86', phone: that.data.phone, verifyCode: that.data.vercode, forceBindWx:0 }).then((res) => {
        if (res && res.code == 200) {
          wx.setStorageSync('token', res.data.token);
          app.globalData.token = res.data.token;
          var userInfo = res.data.user
          if (userInfo && !userInfo.avatarUrl) {
            userInfo.avatarUrl = version.defaultAvataUrl
          }
          wx.setStorageSync('userInfo', userInfo);
          app.globalData.userInfo = userInfo
          app.globalData.hasUserInfo = true
          app.globalData.auth = true
          wx.setStorageSync('auth', true);
          let phone = userInfo.phone
          app.globalData.hasPhone = true
          wx.setStorageSync('hasPhone', true);
          that.setData({
            hasPhone: true,
            isShow: false,
          })
        
          that.triggerEvent('myevent', {
            paramBtoA: {
              userInfo: app.globalData.userInfo,
              hasUserInfo: true,
              auth: true,
              hasPhone: true,
            }
          })
        } else {
          wx.showModal({
            title: '错误提示',
            content: '验证码输入错误！'
          })
          this.setData({
            vercode: ''
          })
        }

      })

    },

    // 新
    //隐藏弹框
    hideAuth() {
      this.setData({
        isShow: false
      })
    },
    //展示弹框
    showAuth() {
      this.setData({
        isShow: true,
        auth: app.globalData.auth,
        userInfo: app.globalData.userInfo,
        hasUserInfo: app.globalData.hasUserInfo,
        hasPhone: app.globalData.hasPhone,
        getUserInfoFail: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
      })
    },
  }
})